package com.abc.invoke.server.service;

import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.ConcurrentMap;

import com.abc.invoke.bean.User;
import com.abc.invoke.bean.UserSessionToken;
import com.abc.invoke.server.db.session.SpringInvokerBackendSession;
import com.abc.invoke.server.db.session.SpringInvokerBackendSessionFactory;
import com.google.common.collect.Maps;

/**
 * 服务器端启动的时候就初始化
 */
public class SessionCache {

	private final ConcurrentMap<BigInteger, SessionCacheEntry> sessions;
	private SpringInvokerBackendSessionFactory sessionFactory;

	public SessionCache() {
		sessions = Maps.newConcurrentMap();
		sessionFactory=new SpringInvokerBackendSessionFactory();
	}

	// 数据库，分布式可能要用到DatabaseContext
	/*
	 * public SessionCache(DatabaseContext db){
	 * sessions=Maps.newConcurrentMap(); }
	 */

	public User login(String name, String password) {
		User u = new User();
		u.setName(name);
		u.setEmail("abc@abc.com");
		u.setAge(20);
		u.setSessionId(this.generateClientId());
		// 创建一个usession,放入cache
		UserSession newSession = new UserSession(u);
		this.addEntry(newSession);
		return u;
	}

	private BigInteger generateClientId() {
		BigInteger clientId = new BigInteger(256, new Random());
		return clientId;
	}

	private void addEntry(UserSession newSession) {
		SessionCacheEntry entry = new SessionCacheEntry(newSession);
		this.sessions.put(newSession.getUser().getSessionId(), entry);
	}

	private SessionCacheEntry getEntry(UserSessionToken userToken) {
		System.out.println(userToken.getUserSessionId().toString());
		for(BigInteger id: sessions.keySet()){
			System.out.println("cu: "+id.toString());
		}
		return this.sessions.get(userToken.getUserSessionId());
	}

	public SpringInvokerBackendSession getSession(UserSessionToken userToken) {
		SessionCacheEntry entry = this.getEntry(userToken);
		return sessionFactory.create(entry.getUser());
	}
}
